package com.hooview.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页
 *
 * @author gavincook
 * @version $ID: Paginator.java, v0.1 2018-01-03 19:37 gavincook Exp $$
 */
public class Paginator<T> {

    /** 总记录数 */
    private long totalItemsCount;

    /** 分页大小 */
    private int pageSize;

    /** 当前页码，从1开始 */
    private int currentPageNum;

    /** 当前分页数据 */
    private List<T> items = new ArrayList<T>();

    public Paginator(Paginator old, List<T> items) {
        this(old.getTotalItemsCount(), items, old.getCurrentPageNum(), old.getPageSize());
    }

    public Paginator(long totalItemsCount, List<T> items, int currentPageNum, int pageSize) {
        this.totalItemsCount = totalItemsCount;
        this.items = items;
        this.pageSize = pageSize <= 0 ? 100 : pageSize;
        this.currentPageNum = currentPageNum;
    }

    public static <T> Paginator<T> ofEmpty(int pageSize) {
        return new Paginator(0, null, 1, pageSize);
    }

    public List<T> getItems() {
        return items;
    }

    public long getTotalPageCount() {
        return ((totalItemsCount / pageSize) + (totalItemsCount % pageSize == 0 ? 0 : 1));
    }

    public long getTotalItemsCount() {
        return totalItemsCount;
    }

    public int getCurrentPageNum() {
        if (currentPageNum <= 1) {
            return 1;
        }
        return currentPageNum;
    }

    public int getPageSize() {
        if (pageSize <= 0) {
            return 1;
        }
        return pageSize;
    }

    public int getNextPageNum() {
        if (this.currentPageNum < getTotalPageCount()) {
            return currentPageNum + 1;
        } else {
            return currentPageNum;
        }

    }

    public int getPreviousPageNum() {
        if (currentPageNum <= 1) {
            return 1;
        } else {
            return currentPageNum - 1;
        }
    }
}
